package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.WebConfig;
import com.gaogzhen.mapper.WebConfigMapper;
import com.gaogzhen.service.WebConfigService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class WebConfigServiceImpl extends ServiceImpl<WebConfigMapper, WebConfig> implements WebConfigService{

    @Override
    public Page<WebConfig> findByPage(Page<WebConfig> page, String name, String type) {
        page.addOrder(OrderItem.desc("sort"));
        return page(page, Wrappers.lambdaQuery(WebConfig.class)
                                    .like(StringUtils.isNotBlank(name), WebConfig::getName, name)
                                    .eq(StringUtils.isNotEmpty(type), WebConfig::getType, type)
        );
    }

    @Override
    public void add(WebConfig webConfig) {
        boolean save = save(webConfig);
        if (!save) {
            throw new RuntimeException("新增资源配置失败！");
        }
    }

    @Override
    public void updateWebConfig(WebConfig webConfig) {
        boolean update = updateById(webConfig);
        if (!update) {
            throw new RuntimeException("更新资源配置失败！");
        }
    }

    @Override
    public void delete(String[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            throw new RuntimeException("删除项不能为空!");
        }
        boolean b = removeByIds(Arrays.asList(ids));
        if (!b) {
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public List<WebConfig> getPcBanners() {
        return list(new LambdaQueryWrapper<WebConfig>()
                        .eq(WebConfig::getType, "WEB_BANNER")
                        .eq(WebConfig::getStatus, 1)
                        .orderByDesc(WebConfig::getSort)
        );
    }
}
